import 'package:flutter/services.dart';

/// FileName number_text_input_formatter
///
/// @Author lax
/// @Date 2023/6/1
///
/// @Description

class NumberTextInputFormatter extends TextInputFormatter {
  /// 允许的小数位数 默认不限制
  final int? digit;

  /// 是否允许负数
  final bool allowNegativeNumbers;

  final double? minValue;

  final double? maxValue;

  NumberTextInputFormatter({
    this.digit,
    this.allowNegativeNumbers = true,
    this.minValue,
    this.maxValue,
  });

  /// 获取小数位数
  static int getValueDigit(String value) {
    if (value.contains(".")) {
      return value.split(".")[1].length;
    } else {
      return 0;
    }
  }

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    if (value == ".") {
      value = "0.";
      selectionIndex++;
    }
    if (value != '') {
      // 不是小数
      final doubleValue = double.tryParse(value == '-' ? '0' : value);
      if (doubleValue == null) {
        value = oldValue.text;
        selectionIndex = oldValue.selection.end;
      }
      // 小数位数超出
      if (digit != null && getValueDigit(value) > digit!) {
        value = oldValue.text;
        selectionIndex = oldValue.selection.end;
      }
      // 不能有小数
      if (digit == 0 && value.contains('.')) {
        value = oldValue.text;
        selectionIndex = oldValue.selection.end;
      }
      // 不能有负数
      if (!allowNegativeNumbers && value.contains('-')) {
        value = oldValue.text;
        selectionIndex = oldValue.selection.end;
      }
      // 超出范围
      if (minValue != null && doubleValue != null && doubleValue < minValue!) {
        value = oldValue.text;
        selectionIndex = oldValue.selection.end;
      }
      if (maxValue != null && doubleValue != null && doubleValue > maxValue!) {
        value = oldValue.text;
        selectionIndex = oldValue.selection.end;
      }
    }
    return TextEditingValue(
      text: value,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
